const Router = require('koa-router')
const router = new Router()
const bcrypt = require('bcrypt')
const saltRounds = 10;
const salt = bcrypt.genSaltSync(saltRounds);
const jwt = require('jsonwebtoken')
const tokenSecret = require('../../config/keys.js').tokenSecret
const passport = require('koa-passport')
const gravatar = require('gravatar')

// 引入 User
const User = require('../../models/User')

/**
 * @desc 测试
 * @access public
 */
router.get('/test', async ctx => {
  ctx.status = 200
  ctx.body = {
    msg: 'wujh'
  }
})

/**
 * @desc 注册
 * @access public
 */


router.post('/register', async ctx => {
  // 到数据库查询邮箱是否存在
  const findResult = await User.find({
    email: ctx.request.body.email
  })
  // 邮箱存在
  if (findResult.length > 0) {
    ctx.body = {
      code: -1,
      msg: "邮箱已存在！"
    }
  }
  // 邮箱不存在
  else {
    let newUser = new User({
      name: ctx.request.body.name,
      email: ctx.request.body.email,
      password: ctx.request.body.password,
      avatar: gravatar.url(ctx.request.body.email, {s: '200', r: 'pg', d: 'mm'})
    })
    await newUser.save().then(user => {
      ctx.body = {
        code:1,
        msg:"注册成功"
      }
    }).catch(err => {
      console.log(err);
    })
  }
})

/**
 * @desc 登陆
 * @access public
 */

router.post('/login', async ctx => {
  // 判断邮箱或密码是否提交
  const {email, pwd} = ctx.request.body
  console.log(email, pwd)

  if (!(email && pwd)) {
    ctx.body = {
      code: -1,
      msg: "请保证用户名和密码的完整性"
    }
    return
  }
  let findResult = await User.findOne({email: ctx.request.body.email})
  if (findResult) {
    const {id, name, email} = findResult

    // 验证密码
    let result = await bcrypt.compareSync(pwd, findResult.password)
    console.log(result);
    if (!result) {
      ctx.body = {
        code: -1,
        msg: '用户名或密码错误'
      }
    }

    // 通过验证
    if (result) {
      //生成token
      const payload = {
        id,
        name,
        email
      }
      const token = jwt.sign(payload, tokenSecret, {
        expiresIn: 60 * 60
      })

      ctx.body = {
        code: 1,
        msg: 'success',
        token: "Bearer " + token
      }
    }

  } else {
    ctx.body = {
      code: -1,
      msg: '用户不存在'
    }
  }

  console.log(findResult);
})

/**
 * @desc 获取用户信息
 * @access private
 */

router.get('/current', passport.authenticate('jwt', {session: false}), async ctx => {
  const {_id:id,name,avatar,email} = ctx.state.user


  ctx.body = {
    id,name,avatar,email
  }


})

module.exports = router.routes()
